package it.slkfarm.android;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import it.slkfarm.adapter.CropAdapter;
import it.slkfarm.bean.Crop;
import it.slkfarm.bean.Farm;
import it.slkfarm.bean.Production;
import it.slkfarm.bean.ProductionBean;
import it.slkfarm.helpers.DialogBuilder;
import it.slkfarm.http.HttpConnector;
import it.slkfarm.log.LogData;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SlidingDrawer;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class CropSummary extends Base implements OnClickListener, Runnable
{
	/**
	 * @uml.property  name="production"
	 * @uml.associationEnd  
	 */
	private Production production;
	/**
	 * @uml.property  name="summary"
	 * @uml.associationEnd  
	 */
	private ListView summary;
	/**
	 * @uml.property  name="send"
	 * @uml.associationEnd  
	 */
	private Button send;
	/**
	 * @uml.property  name="close"
	 * @uml.associationEnd  
	 */
	private Button close;
	/**
	 * @uml.property  name="add1"
	 * @uml.associationEnd  
	 */
	private Button add1;
	/**
	 * @uml.property  name="add5"
	 * @uml.associationEnd  
	 */
	private Button add5;
	/**
	 * @uml.property  name="add10"
	 * @uml.associationEnd  
	 */
	private Button add10;
	/**
	 * @uml.property  name="add50"
	 * @uml.associationEnd  
	 */
	private Button add50;
	/**
	 * @uml.property  name="add100"
	 * @uml.associationEnd  
	 */
	private Button add100;
	/**
	 * @uml.property  name="remove1"
	 * @uml.associationEnd  
	 */
	private Button remove1;
	/**
	 * @uml.property  name="remove5"
	 * @uml.associationEnd  
	 */
	private Button remove5;
	/**
	 * @uml.property  name="remove10"
	 * @uml.associationEnd  
	 */
	private Button remove10;
	/**
	 * @uml.property  name="remove50"
	 * @uml.associationEnd  
	 */
	private Button remove50;
	/**
	 * @uml.property  name="remove100"
	 * @uml.associationEnd  
	 */
	private Button remove100;
	/**
	 * @uml.property  name="connector"
	 * @uml.associationEnd  
	 */
	private HttpConnector connector;
	/**
	 * @uml.property  name="secretKey"
	 */
	private String secretKey;
	/**
	 * @uml.property  name="builder"
	 * @uml.associationEnd  
	 */
	private DialogBuilder builder;
	/**
	 * @uml.property  name="dialog"
	 * @uml.associationEnd  
	 */
	private Dialog dialog;
	/**
	 * @uml.property  name="progress"
	 * @uml.associationEnd  
	 */
	private Dialog progress;
	/**
	 * @uml.property  name="labelProgress"
	 * @uml.associationEnd  
	 */
	private TextView labelProgress;
	/**
	 * @uml.property  name="tv"
	 * @uml.associationEnd  
	 */
	private TextView tv;
	/**
	 * @uml.property  name="name"
	 * @uml.associationEnd  
	 */
	private TextView name;
	/**
	 * @uml.property  name="total"
	 * @uml.associationEnd  
	 */
	private TextView total;
	/**
	 * @uml.property  name="productionList"
	 */
	private List<ProductionBean> productionList;
	/**
	 * @uml.property  name="slide"
	 * @uml.associationEnd  
	 */
	private SlidingDrawer slide;
	/**
	 * @uml.property  name="selected"
	 */
	private int selected;
	/**
	 * @uml.property  name="maxQuantity"
	 */
	private int maxQuantity;
	/**
	 * @uml.property  name="toast"
	 * @uml.associationEnd  
	 */
	private Toast toast;
	
	@Override
	public void onCreate(Bundle savedInstanceState)  
	{
		super.onCreate(savedInstanceState);
		setLanguage(dbAdapter.getSetLanguage());
		setContentView(R.layout.summary);
		builder = new DialogBuilder(this, dbAdapter.getSetLanguage());
		secretKey = getIntent().getStringExtra(getPackageName() + ".secretKey");
		Typeface tf = getTypeface();
		tv = (TextView) findViewById(R.id.tvSummaryTitle);
		tv.setTypeface(tf);
		tv = (TextView) findViewById(R.id.tvQuantityTitle);
		tv.setTypeface(tf);
		name = (TextView) findViewById(R.id.tvCropQuantity);
		name.setTypeface(tf);
		total = (TextView) findViewById(R.id.tvTotal);
		total.setTypeface(tf);
		send = (Button) findViewById(R.id.btnSendProduction);
		send.setTypeface(tf);
		send.setOnClickListener(this);
		production = ((CropTabView)this.getParent()).getProduction();
		slide = (SlidingDrawer) findViewById(R.id.sliding);
		summary = (ListView) findViewById(R.id.listSummary);
		summary.setItemsCanFocus(true);
		summary.setOnItemClickListener(new OnItemClickListener() 
		{
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
			{
				selected = arg2;
				int max = production.getCropSelection().get(arg2).getMaxProduction();
				int currentP = production.getCropSelection().get(arg2).getCurrentProduction();
				int remains = max-currentP;
				maxQuantity = (remains * 5) / 100;
				name.setText(production.getCropSelection().get(arg2).getCropName() + " (" + production.getCropSelection().get(arg2).getCultivarName()+")");
				total.setText(R.string.total);
				total.setText(total.getText()+ " " + String.valueOf(production.getCropSelection().get(selected).getQuantity())+"q/"+String.valueOf(maxQuantity)+"q");
				if (production.getCropSelection().get(arg2).getProductionId() == -1)
				{
					send.setVisibility(View.GONE);
					slide.animateOpen();	
				}
				else
				{
					dialog = builder.createDialogTwoButtons(R.string.attention, R.string.update_production);
					dialog.show();
					
					dialog.setOnDismissListener(new OnDismissListener() 
					{	
						public void onDismiss(DialogInterface dialog) 
						{
							if (builder.isUpdate())
							{
								send.setVisibility(View.GONE);
								slide.animateOpen();
							}
						}
					});
				}
			}
		});
		loadList();
		close = (Button) findViewById(R.id.btnCloseQuantity);
		close.setTypeface(tf);
		close.setOnClickListener(this);
		add1 = (Button) findViewById(R.id.btnAdd1);
		add1.setOnClickListener(this);
		add1.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/KMKDSP__.ttf"));
		add5 = (Button) findViewById(R.id.btnAdd5);
		add5.setOnClickListener(this);
		add5.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/KMKDSP__.ttf"));
		add10 = (Button) findViewById(R.id.btnAdd10);
		add10.setOnClickListener(this);
		add10.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/KMKDSP__.ttf"));
		add50 = (Button) findViewById(R.id.btnAdd50);
		add50.setOnClickListener(this);
		add50.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/KMKDSP__.ttf"));
		add100 = (Button) findViewById(R.id.btnAdd100);
		add100.setOnClickListener(this);
		add100.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/KMKDSP__.ttf"));
		
		remove1 = (Button) findViewById(R.id.btnRemove1);
		remove1.setOnClickListener(this);
		remove5 = (Button) findViewById(R.id.btnRemove5);
		remove5.setOnClickListener(this);
		remove10 = (Button) findViewById(R.id.btnRemove10);
		remove10.setOnClickListener(this);
		remove50 = (Button) findViewById(R.id.btnRemove50);
		remove50.setOnClickListener(this);
		remove100 = (Button) findViewById(R.id.btnRemove100);
		remove100.setOnClickListener(this);	
	}
	
	@Override
	public void onResume()
	{
		Log.i("summay", "resume");
		super.onResume();
		production = ((CropTabView)this.getParent()).getProduction();
		loadList();
	}
	
	private void loadList()
	{
		if (production.getCropSelection().size() > 0)
		{
			summary.setAdapter(new CropAdapter(this, R.layout.crop_row_summary_final, production.getCropSelection(), false, dbAdapter.getSetLanguage()));
			send.setBackgroundResource(R.drawable.button);
			send.setEnabled(true);
		}	
		else
		{
			send.setBackgroundResource(R.drawable.button_disabled);
			send.setEnabled(false);
		}
	}

	public void onClick(View v) 
	{
		if (v.getId() == send.getId())
		{
			if (production.getCropSelection().size()>0)
			{
				if (controlQuantity())
				{
					progress = builder.createProgressDialog();
					labelProgress = (TextView) progress.findViewById(R.id.tvCustomProgressLabel);
					progress.show();
					new Thread(this).start();
				}
				else
				{
					toast = builder.createToast(R.string.zero, null, CropSummary.this);
					toast.show();
				}
				
			}
			else
			{
				send.setEnabled(false);
				send.setBackgroundResource(R.drawable.button_disabled);
				toast = builder.createToast(R.string.nullCrop, null, CropSummary.this);
				toast.show();
			}
		}
		else if (v.getId() == close.getId())
		{
			slide.animateClose();
			send.setVisibility(View.VISIBLE);
			loadList();
		}
		else if (v.getId() == add1.getId())
			addQuantity(1);
		else if (v.getId() == add5.getId())
			addQuantity(5);
		else if (v.getId() == add10.getId())
			addQuantity(10);
		else if (v.getId() == add50.getId())
			addQuantity(50);
		else if (v.getId() == add100.getId())
			addQuantity(100);
		else if (v.getId() == remove1.getId())
			removeQuantity(1);
		else if (v.getId() == remove5.getId())
			removeQuantity(5);
		else if (v.getId() == remove10.getId())
			removeQuantity(10);
		else if (v.getId() == remove50.getId())
			removeQuantity(50);
		else if (v.getId() == remove100.getId())
			removeQuantity(100);
	}
	
	private void addQuantity(int q)
	{
		int current = production.getCropSelection().get(selected).getQuantity() + q;
		if (!(current>maxQuantity))
		{
			LogData log = new LogData("CropSummary","Add quantity","Add quantity: "+String.valueOf(q));
			logger.appendLog(log);
			production.getCropSelection().get(selected).setQuantity(production.getCropSelection().get(selected).getQuantity()+q);
			total.setText(R.string.total);
			total.setText(total.getText()+ " " + String.valueOf(production.getCropSelection().get(selected).getQuantity())+"q/"+String.valueOf(maxQuantity)+"q");
		}
		else
		{
			LogData log = new LogData("CropSummary","Add quantity","Error out of range");
			logger.appendLog(log);
			toast = builder.createToast(R.string.no_add, null, CropSummary.this);
			toast.show();
		}
	}
	
	private void removeQuantity(int q)
	{
		int current = production.getCropSelection().get(selected).getQuantity() - q;
		if (!(current<0))
		{
			LogData log = new LogData("CropSummary","Remove quantity","Remove quantity: "+String.valueOf(q));
			logger.appendLog(log);
			production.getCropSelection().get(selected).setQuantity(current);
			total.setText(R.string.total);
			total.setText(total.getText()+ " " + String.valueOf(current)+"q/"+String.valueOf(maxQuantity)+"q");
		}
		else
		{
			LogData log = new LogData("CropSummary","Remove quantity","Error out of range");
			logger.appendLog(log);
			toast = builder.createToast(R.string.no_remove, null, CropSummary.this);
			toast.show();
		}
	}
	
	public boolean controlQuantity()
	{
		boolean result = true;
		int i=0;
		while(result)
		{
			if (production.getCropSelection().get(i).getQuantity() == 0)
			{
				result = false;
				break;
			}
			i++;
			if (i>=production.getCropSelection().size())
				break;
		}
		return result;
	}

	public void run() 
	{
		Farm farm = production.getFarm();
		productionList = new ArrayList<ProductionBean>();
		boolean toUpdate = true;
		for (int i=0; i<production.getCropSelection().size(); i++)
		{
			Crop c = production.getCropSelection().get(i);
			ProductionBean p = new ProductionBean();
			p.setFarmId(farm.getId());
			p.setCultivarId(c.getCultivarId());
			p.setQuantity(c.getQuantity());
			p.setCropId(c.getCropId());
			if (c.getQuantity() > 0)
			{
				List<NameValuePair> nameValuePairs = null;
				int productionId = dbAdapter.getProductionId(c.getCultivarId(), c.getCropId(), farm.getId());
				if (productionId == -1)
				{	
					Date d = new Date();
			        nameValuePairs = new ArrayList<NameValuePair>(8);
					nameValuePairs.add(new BasicNameValuePair("tag", TAG_PRODUCTION));
					nameValuePairs.add(new BasicNameValuePair("control", INSERT));
					nameValuePairs.add(new BasicNameValuePair("secretkey",secretKey));
					nameValuePairs.add(new BasicNameValuePair("farmid",String.valueOf(farm.getId())));
					nameValuePairs.add(new BasicNameValuePair("cropid", String.valueOf(c.getCropId())));
					nameValuePairs.add(new BasicNameValuePair("cultivarid",String.valueOf(c.getCultivarId())));
					nameValuePairs.add(new BasicNameValuePair("quantity", String.valueOf(c.getQuantity())));
					nameValuePairs.add(new BasicNameValuePair("timestamp", String.valueOf(d.getTime()).substring(0, 10)));
					toUpdate = true;
				}
				else
				{
					int quantity = dbAdapter.getQuantity(productionId);
					if (quantity != c.getQuantity())
					{
						nameValuePairs = new ArrayList<NameValuePair>(6);
						nameValuePairs.add(new BasicNameValuePair("tag", TAG_PRODUCTION));
						nameValuePairs.add(new BasicNameValuePair("secretkey",secretKey));
						nameValuePairs.add(new BasicNameValuePair("control", UPDATE));
						nameValuePairs.add(new BasicNameValuePair("farmid",String.valueOf(farm.getId())));			
						nameValuePairs.add(new BasicNameValuePair("productionid", String.valueOf(productionId)));
						nameValuePairs.add(new BasicNameValuePair("quantity", String.valueOf(c.getQuantity())));
						toUpdate = true;
					}
					else
						toUpdate = false;
				}			
				connector = new HttpConnector();
				try 
				{
					if (toUpdate)
					{
						if (connector.connect(WEB_SERVICE_URL_PRODUCTION, nameValuePairs) == 200)
						{
							JSONObject json = connector.getJson();
							Log.i("json prod", json.toString());
							int error = json.getInt("error");
							if (error == 0 && productionId == -1)
							{
								p.setProductionId(json.getInt("production_id"));
								p.setUpdate(false);		
							}
							else if (error == 0 && productionId != -1)
							{	
								p.setProductionId(productionId);
								p.setUpdate(true);
							}
							boolean result = dbAdapter.insertOrUpdateProduction(p);
							while(!result)
								result = dbAdapter.insertOrUpdateProduction(p);
							Message msg = handler.obtainMessage();
							msg.obj = "ADD_CROP";
							handler.sendMessage(msg);
							Thread.sleep(750);
						}
						else
						{
							//ERROR SERVER
							sendHandlerMessage("SERVER_NO");
						}
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					sendHandlerMessage("SERVER_NO");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					sendHandlerMessage("SERVER_NO");
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					sendHandlerMessage("SERVER_NO");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
			}
		}
		sendHandlerMessage("DOWNLOAD_CROP");
		updatingCrop(farm);
		sendHandlerMessage("FINISH");
	}
	
	/**
	 * @uml.property  name="handler"
	 * @uml.associationEnd  multiplicity="(1 1)"
	 */
	private Handler handler = new Handler()
	{
		  @Override
	        public void handleMessage(Message msg) 
	        {
			  	String message = (String) msg.obj;
			  	if (message.equalsIgnoreCase("FINISH"))
			  	{
			  		progress.dismiss();
			  		dialog = builder.createDialog(R.string.success, R.string.production_message, null, CropSummary.this);
			  		dialog.show();
			  	}
			  	else if (message.equalsIgnoreCase("SERVER_NO"))
	        	{
	        		progress.dismiss();
	        		dialog = builder.createDialog(R.string.error, R.string.handler_server_no, null, null);
	        		dialog.show();
	        	}
			  	else if (message.equalsIgnoreCase("ERROR_STORAGE"))
				{
					progress.dismiss();
					Dialog dialog = builder.createDialog(R.string.error, R.string.handler_error_storage_production, null, null);
					dialog.show();
				}
			    else if (message.equalsIgnoreCase("ADD_CROP"))
				{
					labelProgress.setText(R.string.sending);
				}
			    else if (message.equalsIgnoreCase("DOWNLOAD_CROP"))
	        	{
	        		labelProgress.setText(R.string.update_crops);
	        	}
	        	else if (message.equalsIgnoreCase("ERROR_CROP"))
				{
					progress.dismiss();
					Dialog dialog = builder.createDialog(R.string.error, R.string.handler_error_crop, null, null);
					dialog.show();
				}
	        	else if (message.equalsIgnoreCase("ERROR_STORAGE_CROP"))
				{
					progress.dismiss();
					Dialog dialog = builder.createDialog(R.string.error, R.string.handler_error_storage_crop, null, null);
					dialog.show();
				}
	        }
	};
	
	public void updatingCrop(Farm farm)
	{
		List<Crop> cropList = new ArrayList<Crop>();
		HttpConnector connector = new HttpConnector();
		try 
		{
			
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
			int lang = dbAdapter.getSetLanguage();
			nameValuePairs.add(new BasicNameValuePair("tag", TAG_GET_CROPS_TEST));
			nameValuePairs.add(new BasicNameValuePair("secretkey",secretKey));
			nameValuePairs.add(new BasicNameValuePair("farmid",String.valueOf(farm.getId())));
			if (lang == 1)
				nameValuePairs.add(new BasicNameValuePair("lang",LOCALE_EN));
			else
				nameValuePairs.add(new BasicNameValuePair("lang", LOCALE_SRILANKA));
			int valueConnect = connector.connect(WEB_SERVICE_URL_CROP, nameValuePairs);
			sendHandlerMessage("TEST");
			Thread.sleep(10000);
			if (valueConnect == 200)
			{
				JSONObject jsonObject = connector.getJson();
				Log.i("json crop", jsonObject.toString());
				int error = jsonObject.getInt("error");
				int success = jsonObject.getInt("success");
				if (error == 0 && success == 1)
				{	
					cropList = new ArrayList<Crop>();
					int numberOfCrops = jsonObject.getInt("number_of_crops");
					int i = 1;
					JSONObject cropInfo = jsonObject.getJSONObject("cropInfo");
					Iterator keyCropInfo = cropInfo.keys();
					//CICLO SU CROP_INFO
					while (keyCropInfo.hasNext())
					{
						String dynamicKey = (String) keyCropInfo.next();
						Log.i("type", dynamicKey);
						JSONObject type = cropInfo.getJSONObject(dynamicKey);
						Iterator keyType = type.keys();
						//CICLO SUI TIPI
						while(keyType.hasNext())
						{
							dynamicKey = (String) keyType.next();
							Log.i("cropName", dynamicKey);
							if (!dynamicKey.equalsIgnoreCase("label"))
							{
								JSONObject cultivar = type.getJSONObject(dynamicKey).getJSONObject("cultivar");
								Iterator keyCultivar = cultivar.keys();
								//CICLO SUI CROP
								while (keyCultivar.hasNext())
								{
									dynamicKey = (String) keyCultivar.next();
									Log.i("cultivarName", dynamicKey);
									JSONObject singleCrop = cultivar.getJSONObject(dynamicKey);
									Crop crop = new Crop();
									crop.setCropId(singleCrop.getInt("cropId"));
									Log.i("cultivarId", String.valueOf(singleCrop.getInt("cultivarId")));
									crop.setCultivarId(singleCrop.getInt("cultivarId"));
									crop.setCropType(singleCrop.getString("cropType"));
									crop.setCropName(singleCrop.getString("cropName"));
									crop.setCultivarName(singleCrop.getString("cultivarName"));
									JSONObject production = singleCrop.getJSONObject("production");
									if(!production.isNull("maxProduction")) 
										crop.setMaxProduction(production.getInt("maxProduction"));
									else
										crop.setMaxProduction(0);
									if (!production.isNull("currentProduction"))
										crop.setCurrentProduction(production.getInt("currentProduction"));
									else
										crop.setCurrentProduction(0);
									if (!production.isNull("percentageOfProduction"))
									{
										double percentage = production.getDouble("percentageOfProduction");
										percentage = Math.floor(percentage*100);
										percentage = percentage / 100;
										crop.setPercentageProduction(percentage);
									}
									else
										crop.setPercentageProduction(0.0);
									String imageName = "";
									imageName = "img"+String.valueOf(crop.getCropId())+String.valueOf(crop.getCultivarId());
									connector.getImage(singleCrop.getString("images"), imageName);
									JSONObject characteristics = singleCrop.getJSONObject("characteristics");
									String app = characteristics.getString("size");
									if (app.equalsIgnoreCase("") || app.equalsIgnoreCase("null"))
										crop.setSize("?");
									else
										crop.setSize(app);
									app = characteristics.getString("weight");
									if (app.equalsIgnoreCase("") || app.equalsIgnoreCase("null"))
										crop.setWeight("?");
									else
										crop.setWeight(app);
									app = characteristics.getString("color");
									if (app.equalsIgnoreCase("") || app.equalsIgnoreCase("null"))
										crop.setColor("?");
									else
										crop.setColor(app);
									cropList.add(crop);
								}
							}	
						}
					}
					LogData log = new LogData("Menu","Json","Get crops list");
					logger.appendLog(log);
					//MEMORIZZARLI
					if (dbAdapter.registerCrops(cropList, farm.getAgroGeolocigalRegionId()) !=0)
					{
						log = new LogData("Menu","Database","Save crops list");
						logger.appendLog(log);
					}
					else
					{
						log = new LogData("Menu","Database","Can't save crops list");
						logger.appendLog(log);
						sendHandlerMessage("ERROR_STORAGE_CROP");
					}
				}
				else
				{
					LogData log = new LogData("Menu","Json error","Can't get crops list");
					logger.appendLog(log);
					sendHandlerMessage("ERROR_CROP");
				}
			}
			else
			{
				LogData log = new LogData("Menu","Server","Can't connect to server");
				logger.appendLog(log);
				sendHandlerMessage("SERVER_NO");
			}
			
		} 
		catch (ClientProtocolException e) 
		{
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
		} catch (IllegalStateException e) {
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
		} catch (JSONException e) {
			
			e.printStackTrace();
		} catch (InterruptedException e) {
			sendHandlerMessage("SERVER_NO");
			e.printStackTrace();
		}
	}
	
	public void sendHandlerMessage(String message)
	{
		Message msg = handler.obtainMessage();
		msg.obj = message;
		handler.sendMessage(msg);
	}
}
